package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 王加鑫
 * @Date 2021/09/09 21:07
 * @Since JDK 1.8
 */
@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 上传小视频返回视频id
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            //校验video是否有效
            if(ObjectUtil.isAllEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())){
                return null;
            }

            //设置id
            video.setId(ObjectId.get());
            video.setVid(this.idService.created(IdType.VIDEO));
            //发布时间
            video.setCreated(System.currentTimeMillis());
            //保存到Mongodb中
            this.mongoTemplate.save(video);
            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    /**
     * 小视频列表
     * 如果有推荐视频，优先返回推荐视频，如果不够或没有，按照时间倒序查询视频表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //从redis中获取推荐视频的数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        //推荐系统的推荐数据
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<String> recommendIds = StrUtil.split(redisData,',');
        //推荐系统推荐的数据用完了
        if(page * pageSize > recommendIds.size()){
            //没有推荐或前面推荐已经查询完毕，查询系统的视频数据
            //计算前面的推荐视频页数
            int totalPage = PageUtil.totalPage(recommendIds.size(), pageSize);
            Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).with(PageRequest.of(page-totalPage-1,pageSize));
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            if(CollUtil.isEmpty(videoList)){
                return pageInfo;
            }
            pageInfo.setRecords(videoList);
            return pageInfo;
        }

        //将推荐id转化为long类型
        List<Long> vids = new ArrayList<>();
        for (String recommendId : recommendIds) {
            vids.add(Convert.toLong(recommendId));
        }

        Query query = Query.query(Criteria.where("vid").in(vids)).with(PageRequest.of(page-1,pageSize));
        List<Video> videoList = this.mongoTemplate.find(query, Video.class);
        if(CollUtil.isEmpty(videoList)){
            return pageInfo;
        }
        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    /**
     * 查询小视频评论的数量
     * @param videoId
     * @param
     * @return
     */
    @Override
    public Long queryVideoCommentCount(String videoId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(videoId)).and("commentType").is(CommentType.LIKE.getType()));
        return this.mongoTemplate.count(query, Comment.class);
    }

    /**
     * 关注用户
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if(ObjectUtil.isAllEmpty(userId, followUserId)) {
            return false;
        }

        try {
            //用户处于关注状态，不能进行重复关注
            if(this.isFollowUser(userId, followUserId)) {
                return false;
            }
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(followUser);
            //保存数据到redis
            //以登录用户和要关注的用户作为联合主键来精准定位这一个key
            String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 取消关注用户
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if(ObjectUtil.isAllEmpty(userId,followUserId)){
            return false;
        }
        //用户不处于关注状态，不能取消关注
        if(!this.isFollowUser(userId,followUserId)){
            return false;
        }

        //将mongodb中的关注数据给移除
        Query query = Query.query(Criteria.where("userId").in(userId).and("followUserId").in(followUserId));
        if(this.mongoTemplate.remove(query,FollowUser.class).getDeletedCount() > 0){
            String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
            String hashKey = String.valueOf(followUserId);
            //同时将redis缓存中的这个标记位删除
            this.redisTemplate.opsForHash().delete(redisKey,hashKey);
            return true;
        }
        return false;
    }

    /**
     * 查询当前用户是否关注某个用户
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
        String hashKey = String.valueOf(followUserId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(data)){
            //如果data有数据就跟标记位比较
            return StrUtil.equals(Convert.toStr(data),"1");
        }
        //缓存中没有数据我们还需去mongodb中再查询一下数据确定
        Query query = Query.query(Criteria.where("userId").in(userId).and("followUserId").in(followUserId));
        long count = this.mongoTemplate.count(query, FollowUser.class);
        return count > 0;
    }

    /**
     * 视频记录翻页
     * @param uid
     * @return
     */
    @Override
    public List<Video> queryVideosList(Integer uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        List<Video> VideoList = this.mongoTemplate.find(query, Video.class);
        return VideoList;
    }
}
